﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.Utils;

namespace 账号管理
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            Action ac = new Action(InitData);
            ac.BeginInvoke(null, null);
        }

        #region 属性
        AccountData CurrentRow
        {
            get { return bsList.Current as AccountData; }
        }
        #endregion

        #region Custom
        private void InitData()
        {

            List<AccountData> datas = DatabaseFactory.CreateDatabase("sqlite").ExecuteDataReader<AccountData>("select id,主题,账号,密码,网站,备注 from 账号", null, dr =>
            {
                return new AccountData
                {
                    Id = dr["id"].GetValue<int>(0),
                    Title = XEncrypt.DES_Decrypt(dr["主题"].GetValue<string>(string.Empty)),
                    Acc = XEncrypt.DES_Decrypt(dr["账号"].GetValue<string>(string.Empty)),
                    Pwd = XEncrypt.DES_Decrypt(dr["密码"].GetValue<string>(string.Empty)),
                    Url = dr["网站"].GetValue<string>(string.Empty),
                    Remark = dr["备注"].GetValue<string>(string.Empty)
                };
            }).ToList();

            bsList.DataSource = datas;
            bsList.ResetBindings(false);
        }
        #endregion
        
        private void gvMain_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.CellValue.IsNullOrEmpty()) return;

            if (e.Column == colUrl)
            {
                if (e.CellValue.ToString().IsNullOrEmpty() == false)
                {
                    Process.Start(e.CellValue.ToString());
                } 
            }
        }

        private void barAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FormAdd main = new FormAdd();
            if (main.ShowDialog() == DialogResult.OK)
            {
                bsList.List.Add(main.Source);
                bsList.ResetBindings(false);
            }
        }

        private void barDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CurrentRow.IsNullOrEmpty()) return;

            IDatabase db = DatabaseFactory.CreateDatabase("sqlite");
            //将记录保存到历史记录
            db.ExecuteNonQuery("insert into 历史账号(账号,密码,主题,网站,备注,账户类型ID) select 账号,密码,主题,网站,备注,账户类型ID from 账号 where ID=" + CurrentRow.Id);
            int count = db.ExecuteNonQuery("delete from 账号 where id=" + CurrentRow.Id);

            if (count > 0)
            {
                bsList.RemoveCurrent();
                bsList.ResetBindings(false);
            }
        }

        private void barKey_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                string key = Guid.NewGuid().ToString();
                KeyValuePair<string, string> keyPair = XEncrypt.CreateRSAKey();
                string privateKey = keyPair.Value;
                string publicKey = keyPair.Key;

                string signedData = XEncrypt.HashAndSignString(key, privateKey);
                DatabaseFactory.CreateDatabase("sqlite").ExecuteNonQuery("delete from 钥匙;Insert into 钥匙(键,签名) values('" + key + "','" + publicKey + "')");
                using (FileStream fs = new FileStream(Path.Combine(Application.StartupPath, "key.xkey"), FileMode.Create))
                {
                    byte[] bSign = signedData.ToByteArray();
                    fs.Write(bSign, 0, bSign.Length);
                    fs.Close();
                }

                MessageBox.Show("生成成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }

        private void gcMain_DoubleClick(object sender, EventArgs e)
        {
            if (!CurrentRow.IsNullOrEmpty())
            {
                FormAdd update = new FormAdd();
                update.SetSource(CurrentRow);
                update.ShowDialog();         
            }
        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void barRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            InitData();
        }

        private void bareditPwd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FormPwd pwd = new FormPwd();
            pwd.ShowDialog();
        }

        private void barExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                sfddata.FileName = "账号数据";
                sfddata.DefaultExt = ".xd";
                sfddata.Filter = "数据文件|*.xd";
                if (sfddata.ShowDialog() == DialogResult.OK)
                {
                    System.IO.Stream fs = sfddata.OpenFile();
                    IDatabase db = DatabaseFactory.CreateDatabase("sqlite");

                    List<AccountData> datas = db.ExecuteDataReader<AccountData>("select 账号,密码,主题,网站,备注 from 账号", null, dr =>
                          {
                              return new AccountData
                              {
                                  Title = dr["主题"].GetValue<string>(string.Empty),
                                  Acc = dr["账号"].GetValue<string>(string.Empty),
                                  Pwd = dr["密码"].GetValue<string>(string.Empty),
                                  Url = dr["网站"].GetValue<string>(string.Empty),
                                  Remark = dr["备注"].GetValue<string>(string.Empty),
                              };
                          }).ToList();

                    byte[] fileByte = datas.ObjectToBytes();
                    fs.Write(fileByte, 0, fileByte.Length);
                    fs.Close();

                    MessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void barImport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                ofdData.Filter = "数据文件|*.xd";
                ofdData.FileName = "账号数据";
                ofdData.Multiselect = false;
                if (ofdData.ShowDialog() == DialogResult.OK)
                {
                    using (FileStream fs = new FileStream(ofdData.FileName, FileMode.Open))
                    {
                        byte[] bFile = fs.ReadAllBinary();
                        List<AccountData> datas = bFile.ByteToObject<List<AccountData>>();
                        if (!datas.IsNullOrEmpty())
                        {
                            IDatabase db = DatabaseFactory.CreateDatabase("sqlite");
                            if (MessageBox.Show("是否清空账号！", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                db.ExecuteNonQuery("delete from 账号", null);//清空账号表
                            }
                            else
                            {
                                foreach (var data in datas)
                                {
                                    db.ExecuteNonQuery("insert into 账号(主题,账号,密码,网站,备注) values (@title,@acc,@pwd,@url,@remark)",
                                    new
                                    {
                                        title = data.Title,
                                        acc = data.Acc,
                                        pwd = data.Pwd,
                                        url = data.Url,
                                        remark = data.Remark,
                                    });
                                }
                            }
                        }
                        MessageBox.Show("导入成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void gridView1_MouseMove(object sender, MouseEventArgs e)
        {
            GridHitInfo hint = this.gridView1.CalcHitInfo(e.X, e.Y);
            if (hint.RowHandle >= 0)
            {
                AccountData data = (AccountData)gridView1.GetRow(hint.RowHandle);//取出当前资料行
                if (data == null) return;

                string hintText = string.Format("账号：{0}\n密码：{1}\n{2}",
                    data.Acc, data.Pwd, data.Url);//显示的内容:货品名称
                SuperToolTip tooltip = new SuperToolTip();

                ToolTipControllerShowEventArgs aa = new ToolTipControllerShowEventArgs();
                aa.AllowHtmlText = DefaultBoolean.True;
                aa.Title = data.Title; //HTML, 粗体
                aa.ToolTip = hintText;//断行
                aa.ShowBeak = true;
                aa.Rounded = true;////圆角
                aa.RoundRadius = 7;//圆角率
                aa.ToolTipType = ToolTipType.SuperTip;//超级样式，可多行或显示图标
                aa.IconType = ToolTipIconType.Information;//消息图标
                aa.IconSize = ToolTipIconSize.Small;//大图标
                aa.ToolTipStyle = ToolTipStyle.Windows7;

                toolTipController1.ShowHint(aa);//显示Hint窗体
            }
            else
            {
                toolTipController1.HideHint();
            }
        }
    }

    /// <summary>
    /// 账号
    /// </summary>
    [Serializable]
    internal class AccountData
    {
        /// <summary>
        /// 主键ID
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 主题
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 账号
        /// </summary>
        public string Acc { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string Pwd { get; set; }
        /// <summary>
        /// 网址
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; set; }
    }

    /// <summary>
    /// 
    /// </summary>
    internal class KeyData
    {
        /// <summary>
        /// 键
        /// </summary>
        public string Key { get; set; }
        /// <summary>
        /// 公共键
        /// </summary>
        public string PlcKey { get; set; }
    }

    internal class UserData
    {
        /// <summary>
        /// 编号
        /// </summary>
        public int ID { get; set; }
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string UserPass { get; set; }
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool Enabled { get; set; }
    }
}
